<?php

class updatepointsPersonTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
     $this->addArguments(array(
       new sfCommandArgument('raidid', sfCommandArgument::REQUIRED, 'My argument'),
       new sfCommandArgument('playerid', sfCommandArgument::REQUIRED, 'My argument'),
       new sfCommandArgument('lastRaidDate', sfCommandArgument::REQUIRED, 'My argument'),
       new sfCommandArgument('lifetimeRaidAttendanceCount', sfCommandArgument::REQUIRED, 'My argument'),
     ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
      new sfCommandOption('raidid', null, sfCommandOption::PARAMETER_REQUIRED, 'Raid ID', '-1'),
      new sfCommandOption('playerid', null, sfCommandOption::PARAMETER_REQUIRED, 'Player ID', '-1'),
    ));

    $this->namespace        = 'raidpoints';
    $this->name             = 'updatepointsPerson';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [updatepoints|INFO] task does things.
Call it with:

  [php symfony updatepoints|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();

    echo "PersonTask";
    $raid = $arguments['raidid'];
    $player = $arguments['playerid'];
    $lastRaidDate = $arguments['lastRaidDate'];
    $withAttendance = true;

    if ($withAttendance)
    {
        $query = Doctrine::getTable("History")
            ->createQuery()
            ->select("convert((dt), date)")
            ->where("value > ?", 0)
            ->andWhere("ttype=?", 'P')
            ->andWhere("playerid=?", $player)
            ->andWhere("raidid=?", $raid)
            ->groupBy("convert((dt), date)")
            ->orderBy("convert((dt), date)")
            ->limit(1);
        $result = $query->execute();
        if ($result->count() > 0)
        {
            $data = $result->getFirst()->toArray();
            //print_r($data);
            $firstRaidDate = strtotime($data["convert"]." GMT");
        }
        else
            $firstRaidDate = $lastRaidDate;
        //echo $data["dt"]." ";
        $query->free();
        unset($query);
        $result->free();
        unset($result);

        // TODO:  Configure this time.
        print_r(sfConfig::get("app_attendance_days"));
        foreach (explode(",",sfConfig::get("app_attendance_days")) as $days)
        {
            $query = Doctrine::getTable("PlayerAttendance")
                ->createQuery()
                ->select()
                ->where("playerid=?", $player)
                ->andWhere("raidid=?", $raid)
                ->andWhere("numdays=?", $days);
            $result = $query->execute();
            $pa = null;
            if ($result->count() == 1)
            {
                $pa = $result->getFirst();
            }
            else
            {
                $pa = new PlayerAttendance();
                $pa->setRaidid($raid);
                $pa->setPlayerid($player);
                $pa->setNumdays($days);
            }
            $lowTime = strtotime("-".$days." days", $lastRaidDate);
//            $highTime = strtotime("+1 day", $lastRaidDate);
//            $highTime = strtotime("-1 second", $highTime);
            $highTime = $lastRaidDate;
            echo "30 days: "."-".$days." days"."\n";
            echo "firstRaidDate: ".$firstRaidDate."\n";
            echo "lastRaidDate: ".$lastRaidDate."\n";
            echo "lowTime: ".$lowTime." ".date("Y-m-d H:i:s", $lowTime)."\n";
            echo "highTime: ".$highTime." ".date("Y-m-d H:i:s", $highTime)."\n";

            $query = Doctrine::getTable("Guildhistory")
                ->createQuery("h")
                ->select("h.dt")
                ->where("h.raidid=?", $raid)
                ->andWhere("h.playerid=?", $player)
                ->andWhere("h.ttype=?", 'P')
                ->andWhere("h.dt >= ?", date("Y-m-d H:i:s", $lowTime))
                ->andWhere("h.dt <= ?", date("Y-m-d H:i:s", $highTime))
                ->addGroupBy("convert((h.dt), date)")
                ->addOrderBy("convert((h.dt), date)");
            $result = $query->execute();
            $attendanceCount = 0;
            if ($result->count() > 0)
                $attendanceCount = $result->count();

            echo "attendanceCount: ".$attendanceCount."\n";

            $query = Doctrine::getTable("Guildhistory")
                ->createQuery("gh")
                ->select("CONVERT((gh.dt), date)")
                ->where("gh.raidid=?", $raid)
                ->andWhere("gh.ttype=?", 'P')
                ->andWhere("gh.dt >= ?", date("Y-m-d H:i:s", $lowTime))
                ->andWhere("gh.dt <= ?", date("Y-m-d H:i:s", $highTime))
                ->groupBy("convert((gh.dt), date)")
                ->orderBy("convert((gh.dt), date)");
            $result = $query->execute();

            $attendance = 0;
            if ($result->count() > 0)
            {
                //$array = $result->getFirst()->toArray();
                $attendance = ( $attendanceCount / (1.0 * $result->count())) * 10000;
            }

            $pa->setPercent($attendance);
            $pa->save();
            echo "attendance: ".$attendance."\n";
        }

        $query = Doctrine::getTable("PlayerAttendance")
            ->createQuery()
            ->select()
            ->where("playerid=?", $player)
            ->andWhere("raidid=?", $raid)
            ->andWhere("numdays=?", 0);
        $result = $query->execute();
        $pa = null;
        if ($result->count() == 1)
        {
            $pa = $result->getFirst();
        }
        else
        {
            $pa = new PlayerAttendance();
            $pa->setRaidid($raid);
            $pa->setPlayerid($player);
            $pa->setNumdays(0);
        }

        $query = Doctrine::getTable("Guildhistory")
            ->createQuery("h")
            ->select("convert((h.dt), date)")
            ->where("value > ?", 0)
            ->andWhere("h.raidid=?", $raid)
            ->andWhere("h.playerid=?", $player)
            ->andWhere("h.ttype=?", 'P')
            ->groupBy("convert((h.dt), date)")
            ->orderBy("convert((h.dt), date)");
        $result = $query->execute();
        $lifetimeCount = 0;
        if ($result->count() > 0)
            $lifetimeCount = $result->count();
        echo "lifetimeCount: ".$lifetimeCount."\n";

        $lifetimeAttendance = 0;
        $lifetimeRaidAttendanceCount = $arguments['lifetimeRaidAttendanceCount'];
        if ($lifetimeRaidAttendanceCount > 0)
        {
            $lifetimeAttendance = ( $lifetimeCount / (1.0 * $lifetimeRaidAttendanceCount)) * 10000;
        }
        echo $lifetimeRaidAttendanceCount." lifetimeAttendance: ".$lifetimeAttendance."\n";

        $pa->setPercent($lifetimeAttendance);
        $pa->save();
        //$ph->setAttendance($attendance);
    }

    // add your code here
  }
}
